// ==UserScript==
// @name        Salon25 NE
// @namespace   http://juljas.net/
// @description Rozszerzenia do engine Salonu24 w odmianie "Nowy Ekran"
// @version     1.1.14
// @copyright   (C) 2008-2012, greasemonkey (greasemonkey.salon24.pl) & Jan Słupski (follow.salon24.pl)
// @icon	http://juljas.net/s24/faq/salon25/salon25.png
// @include     http://*.nowyekran.pl/*
// @exclude     http://*http://*.nowyekran.pl/*
// ==/UserScript==
s25 = {}; 
s25.meta = {};
s25.meta.name =   "Salon25 NE";
s25.meta.version ="1.1.14"


s25.parsemeta = function (cdata) {
  res = {};
  lines = cdata.split('\n');
  var m = new RegExp(/\s*\/\/\s*@([a-zA-Z]+)\s+(.*)/);
  for(var l=0;l<lines.length;l++) {
    if(lines[l].match(m))
      res[lines[l].replace(m,'$1')] = lines[l].replace(m,'$2');
  }
  return res;
}


s25.init = function () {
  
  $ = unsafeWindow.$;

  if(typeof(s25.meta.init) != 'undefined' || typeof($version) != 'undefined') {
    alert(s25.meta.name + ' zainstalowany dwukrotnie (najprawdopodobniej jako dodatek Firefoksa i jako skrypt greasemonkey). Pozbądź się jednej wersji. Menu: Narzędzia->Dodatki');
    return 1;
  }
  
  //s25.meta = s25.parsemeta(s25.metas);
  s25.meta.init = true;

  //$('head').append(s25.elem('script', {src:'http://jscrollpane.kelvinluck.com/script/jquery.mousewheel.js', type:'text/javascript'})); 
}

  s25.state = {
    is_logged : false,
    my_domain : undefined,
    blog_domain : undefined,
    blog_author_id : undefined,
    blog_author_name : undefined,
    post_id : undefined,
    
    watched_new_answers : -1,
    watched_first_link : undefined,
    watched_first_title : 0,
    watched_link : undefined,
    watchedcount_link : undefined,
    watched_cache : undefined,

    newmails : 0,
    newmails_li : undefined,

    add_to_fav : undefined,
    default_menu_names : {},
    advanced_menu_magic : 0,

    comment_template: GM_getValue('comment_template', false),
    comment_template_title: GM_getValue('comment_template_title', ''),
    comment_template_content: GM_getValue('comment_template_content', ''),

    is_ff_extension : false, //FIXME: should be set to true value (if we are extesion not raw GM script)
  };

  s25.consts = {
    domain: 'nowyekran.pl',
    show_last_hash : '#show-last-',
    watch_page_url : 'http://admin.nowyekran.pl/posts-comments-watch/',
    postedit_page_url : 'http://admin.nowyekran.pl/posts-edit/',
    quote_start : "<i>",
    quote_end : "</i>",
    xquote_start : "<div style='font-style: italic; border-left: solid 1px gray; padding-left: 3px'>",
    xquote_end : "</div>\n\n",
    project_url : 'http://code.google.com/p/salon25/',
    admin_url : 'http://admin.nowyekran.pl/',
    admin_goto_url : 'http://admin.nowyekran.pl/posts#j-',
    admin_goto_hash : 'j-',
    update_delay : GM_getValue("update_delay", 60),
    version_check_url : "https://salon25.googlecode.com/svn/wiki/WersjaNE.wiki",
    default_blogroll : ['my-content', 'my-last-in-newspapers', 'my-last-posts', 'my-last-comments', 'my-popular-posts', 'my-last-discussions'], //'my-archive', 'my-tags'
  };

  s25.media = {
    //xxd -i lock.png | xargs echo | sed -e 's/0x/%/g' -e 's/, //g' -e 's/%50%4e%47/PNG/g'
    lock :  "data:image/png,%89PNG%0d%0a%1a%0a%00%00%00%0d%49%48%44%52%00%00%00%10%00%00%00%10%02%03%00%00%00%62%9d%17%f2%00%00%00%01%73%52%47%42%00%ae%ce%1c%e9%00%00%00%0c%50%4c%54%45%79%79%79%a0%a0%a0%ca%ca%ca%ff%ff%ff%00%e3%1d%01%00%00%00%34%49%44%41%54%08%d7%63%f8%0f%04%0c%10%e2%49%3d%90%98%1e%0d%24%a2%a7%03%89%fc%e7%40%c2%fe%f3%7f%86%3f%0c%0c%40%62%d5%0a%20%31%73%06%0a%01%16%03%c9%c2%4d%01%00%30%a4%33%ca%33%2a%d7%03%00%00%00%00%49%45%4e%44%ae%42%60%82",
    throbbericon :"data:image/gif,GIF89a%0D%00%0D%00%84%1E%00%00%00%00%08%73%BD%0C%7B%BD%18%7B%C6%1C%84%C6%35%90%CA%46%9C%CE%5A%A2%D3%6B%AF%D8%8B%BF%E1%B5%B5%B5%A0%CE%E7%B5%D6%EF%BD%BD%BD%BD%DE%EF%C6%C6%C6%CE%CE%CE%D6%D6%D6%DE%DE%DE%CA%E2%F3%D6%E7%F7%DE%EF%F7%E7%E7%E7%E7%EF%F7%E7%F7%FF%EF%EF%EF%EF%F7%FF%F7%F7%F7%F7%F7%FF%F7%FF%FF%FF%FF%FF%FF%FF%FF%21%FF%0B%4E%45%54%53%43%41%50%45%32%2E%30%03%01%00%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%59%E0%27%7E%54%82%2C%D5%38%56%46%E0%BA%87%B6%0A%81%40%04%37%CE%89%6D%51%25%81%C4%E4%86%20%D5%2E%1E%60%C2%33%71%69%16%01%84%27%19%9C%B6%18%88%2A%75%E9%C9%26%80%52%0F%E3%C0%B0%06%18%94%E3%74%DD%0C%C8%7A%15%F6%20%2A%AA%D0%02%06%44%4B%37%BA%EC%5F%08%32%2A%24%0B%27%29%23%21%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%47%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%47%21%16%E9%EA%71%44%30%BC%2A%4F%22%60%70%88%2E%AB%8A%4C%69%73%9C%10%A2%83%4A%BA%58%7C%A4%9F%0B%C2%35%72%4C%64%2C%91%C0%33%8A%75%59%E6%AB%ED%B3%0E%47%91%2B%E4%69%15%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%3F%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%CA%AD%A2%E7%4D%C2%38%7D%C1%E8%39%85%9E%C0%23%3A%B0%8C%01%02%0D%25%48%D0%10%28%55%81%F5%C9%AD%1C%BC%56%61%27%E2%A6%46%D3%98%48%63%5A%CE%56%5E%F2%28%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%A8%E7%4D%9F%80%EB%73%FA%38%12%C8%84%8D%71%4A%88%9C%81%68%E0%83%44%31%0E%D8%C3%72%77%03%7E%86%A2%D5%4D%05%FB%18%8A%1F%02%67%74%61%21%C0%A3%DD%49%2C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%E2%E2%F1%14%7A%27%84%A8%26%48%78%6A%8B%C5%A7%F6%D9%05%02%84%A3%63%22%53%39%0A%81%8F%C0%33%8A%8D%1C%82%95%79%7A%FC%B4%79%53%60%F0%73%5A%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%40%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%03%AA%F6%89%D9%44%09%E0%0A%21%AA%F0%2A%4A%D2%47%30%4A%04%0C%8E%5D%AB%A0%E3%10%78%A8%ED%4A%63%3A%12%51%3A%11%79%14%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%45%E0%27%7E%D4%87%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%58%C2%77%E0%9A%22%47%C2%81%62%9C%12%22%E4%E8%A8%4C%7E%12%9E%0F%8D%51%1A%25%02%D0%49%0B%55%B9%26%26%03%2E%8F%10%C8%11%38%A3%0B%0B%F1%43%95%4E%AB%51%08%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%46%E0%27%7E%D3%97%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%02%57%E8%9D%10%A2%1A%F2%53%5B%2C%98%BD%80%00%27%72%94%02%9F%42%60%E1%19%09%BA%A2%C1%CC%E3%F1%AD%62%D9%43%31%CB%1B%1D%80%41%13%2B%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%83%E8%54%FB%C4%50%9C%04%CF%06%23%F0%10%A3%19%49%14%30%50%80%1F%C7%AE%45%98%60%75%A8%16%6C%A4%31%31%8B%28%F0%A7%3C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%F7%17%68%89%0F%E1%40%3C%30%50%8C%53%60%29%0A%7E%4E%CE%42%62%9A%70%88%68%8C%9D%E0%E2%F1%8C%26%AD%51%61%D5%AB%C0%3E%86%53%8D%33%BA%B0%10%AE%D4%EE%44%16%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%63%CC%8A%97%1C%18%94%91%83%B7%F8%18%08%81%00%02%57%F8%38%4E%08%CE%E9%83%10%D5%8A%9F%83%C7%53%89%AA%1C%13%D9%EE%23%F0%E4%BE%2C%5D%B6%F9%61%8F%B3%BD%55%6F%AA%0A%01%00%21%F9%04%01%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%A2%C5%C8%AD%41%2C%0E%E3%C4%16%C1%22%EA%02%8F%E8%E0%71%7C%04%23%C3%CA%E3%39%AC%50%08%D6%47%23%B2%95%90%2B%63%A0%55%D0%FD%56%DC%8F%52%44%15%BD%56%B3%95%77%8A%0A%01%00%3B",
  };


  s25.debug = {
    verbose : 0,
    time : 0,
    time_start: undefined,
  };

 

s25.URL = {

  matches : function() {
    var ret = false;
    for(var i=0; i<arguments.length;i++) {
      if(document.location.href.match(arguments[i]) != null) {
        ret = true;
        break;
      } 
    }
    return ret;
  }

};



s25.update_mpage = function () {
  if(!s25.URL.matches('http://nowyekran.pl/$') && !s25.URL.matches('http://www.nowyekran.pl/$')) return;

  s25.mpage_unnamed_block_title();

  //s25.mpage_hide_avatars();
  if(GM_getValue("sg_hide_avatars", false))
    $('ul.post_list>li>a>img.post_list_awatar').parent().remove();


}



s25.rebuild_ne_main_page = function () {
  if(!s25.URL.matches('http://nowyekran.pl/$') && !s25.URL.matches('http://www.nowyekran.pl/$')) return;

  $('.content-left-column-left>.box').before($('.content-right-column>.box')[0]);
  $('..content-right-column>.adbox').before($('.content-right-column>.box')[0]);

  s25.mpage_unnamed_block_title();

  //$('.content-left-column-left>.box').contents().replaceWith($('.sg_last_post_body'));
}
  

s25.undef = function (obj) {
  return typeof(obj)=='undefined';
}

s25.elem = function (tag, params, childNodes) { 
  // deprecated. use $el
  // todo: refactor code to use $el
  if(typeof(childNodes)=='undefined') childNodes = [];
  if(typeof(params)=='undefined') params = {};

  var ret = document.createElement(tag);
  for(var param in params) {
    if(typeof(params[param])=='string') {
      ret[param] = params[param];
    } else if(typeof(params[param])=='function') {
      addEvent(ret, param, params[param]);
    } else {
      for(var k in params[param]) {
        ret[param][k] = params[param][k];
      }
    }
  }

  for(var i=0;i<childNodes.length;i++) {
    if(typeof(childNodes[i]) == 'string')
      ret.appendChild(document.createTextNode(childNodes[i]));
    else
      ret.appendChild(childNodes[i]);
  }

  return ret;
}

s25.el = function () { 
  var args = Array.prototype.slice.call(arguments);
  var tag = args[0];
  var params = args.length>1 ? args[1] : {};
  var childNodes = args.length>2 ? args.slice(2) : [];

  var ret = document.createElement(tag);
  for(var param in params) {
    if(typeof(params[param])=='string') {
      ret[param] = params[param];
    } else if(typeof(params[param])=='function') {
      s25.addEvent(ret, param, params[param]);
    } else {
      for(var k in params[param]) {
        ret[param][k] = params[param][k];
      }
    }
  }

  for(var i=0;i<childNodes.length;i++) {
    //GM_log(childNodes[i]);
    //GM_log(typeof(childNodes[i]));
    if(typeof(childNodes[i]) == 'string')
      ret.appendChild(document.createTextNode(childNodes[i]));
    else
      ret.appendChild(childNodes[i]);
  }

  return ret;
}

s25.addEvent = function (obj, evType, fn) {
  if(!obj) return false;
  if (obj.addEventListener) {
    obj.addEventListener(evType, fn, false);
    return true;
  } else if (obj.attachEvent) {
    var r = obj.attachEvent("on" + evType, fn);
    return r;
  } else {
    return false;
  }
}

s25.loadPage = function (address, onLoad, onError) {
  //s25.log('GM_xmlhttpRequest(' + address + ')');
  GM_xmlhttpRequest({
    method: 'GET',
    url: address,
    headers: {
      'Cookie': document.cookie,
      //'Accept-Charset': 'ISO-8859-2',
      'X-Requested-With': 'XMLHttpRequest',
    },
    onload: function(responseDetails) {
      //s25.log('status:' + responseDetails.status);
      if(responseDetails.status != 200) {
	//hideLoadingInfo();
	s25.log('status:\n' + responseDetails.status);
	s25.log('statustext:\n'+responseDetails.statusText);
	s25.log('responsetext:\n'+responseDetails.responseText);
	return;
      }	

      if(onLoad) onLoad(responseDetails);
    },
    onerror: function(responseDetails) {
      s25.log('status:\n' + responseDetails.status);
      s25.log('statustext:\n'+responseDetails.statusText);
      s25.log('responsetext:\n'+responseDetails.responseText);
      //hideLoadingInfo();
      if(onError) onError(responseDetails);
    }
  });
}

//process jump to comment directive (#show-last-n)
s25.update_comments_jumpto = function (cinfo) {
  //GM_log("update_comments_jumpto");
  if(!cinfo.length) {
    GM_log("No comments available");
    return;
  }

  if(document.location.hash.indexOf(s25.consts.show_last_hash) != 0)
    return;
  
  //s25.log(document.location.hash);
  jumpto = cinfo.length - parseInt(document.location.hash.slice(s25.consts.show_last_hash.length));
  
  //document.location.hash = cinfo[jumpto].commentname;
  //s25.log(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
  document.location.replace(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
}



s25.update_footer = function () {
  var footerlinks = $('div#footer_body>ul>li');
  if(footerlinks.length) {
    about = s25.createLink(s25.consts.project_url, s25.meta.name);
    if(s25.state.is_logged)
      about = s25.createLink(s25.consts.admin_url + 'mail/#salon25', s25.meta.name);
    else
      about = s25.createLink(s25.consts.admin_url + 'login/#salon25', s25.meta.name);
    about.title = s25.meta.name + ', ver. ' + s25.meta.version + ' - konfiguracja';
    about.style.color = 'red';

    footerlinks.last().removeClass('last').after(s25.elem('li', {className: 'last'}, [about]));

    //footerlinks.style.width='550px';
  }
}

s25.createLink = function(url, text, params)  {
  if(!params) params = {};
  params.href = url;
  params.innerHTML = text != undefined ? text : url;
  a = s25.elem('a', params);
  return a;
}

s25.log = function (msg, verbose) {
  if(!verbose && !s25.debug.verbose)
    return;
  GM_log(msg);
}

//obsługa "admin-forward"
s25.process_url = function () {
  gotolen = s25.consts.admin_goto_hash.length;
  //s25.log('hash: ' + document.location.hash.slice(0,gotolen+1) + ' ' + document.location.hash.slice(gotolen+1));

  if(document.location.hash == '#favpostok') {
    //window.location.hash = "";
    to = window.location.href.replace(/#.*/,'#');
    window.location.replace(to);
    return 1;
  }

  //jeśli właśnie weszliśmy do skrzynki odbiorczej, to nie mamy "nowej" poczty
  if(document.location.href == s25.consts.admin_url + 'mail/') {
    //s25.state.newmails = 0;
    GM_setValue("newmails", 0);
  }


  if(document.location.hash.slice(0,gotolen+1) == '#' + s25.consts.admin_goto_hash) {
    to = document.location.hash.slice(gotolen+1);

    dest = 'back';
    if(to.indexOf(dest) == 0 && dest.length == to.length) {
      window.history.go(-2);
      return 1;
    }

    gotourl = null;

    dest = 'mail-new/';
    if(to.indexOf(dest) == 0) {
      uid = parseInt(to.slice(dest.length));
      if(!uid || uid<0)
	return -1;
      gotourl = s25.consts.admin_url + dest + uid;
    }

    dest = 'posts-edit/';
    if(to.indexOf(dest) == 0) {
      if(dest.length == to.length) 
	gotourl = s25.consts.admin_url + dest;
      else {
	pid = parseInt(to.slice(dest.length));
	if(!pid || pid<0)
	  return -1;
	gotourl = s25.consts.admin_url + dest + pid;
      }
    }

    if(gotourl) {
      //s25.log('going to: ' + gotourl);
      document.location.replace(gotourl);
      //document.location.hash = s25.consts.admin_goto_hash + 'back';
      //document.location = gotourl;
      return 1;
    }
  }

  if(document.location.href == 'http://www.nowyekran.pl/static/about#mclose')  
  {
    GM_log('close');
    unsafeWindow.parent.Service.login();
    window.close();

  }
  if(document.location.href == 'http://www.nowyekran.pl/static/about#mlogin') 
  {
    $('div#body').remove();
    $('login-burl').attr('value', 'http://www.nowyekran.pl/static/about#mclose');
    $('login-burl').attr('value', 'http://www.nowyekran.pl/static/about#mclose');
    $('#jqmLogin').css('left', '0').css('margin-left', '0').css('top', '0');

    unsafeWindow.Service.login('http://www.nowyekran.pl/static/about#mclose','http://www.nowyekran.pl/static/about#mclose');
  }


  return 0;
}


s25.check_is_logged = function () {

  s25.state.my_domain = undefined;
  s25.state.is_logged = false;

  if(unsafeWindow.Service.isLogin()) {
    if($.cookie('s_us_nick')) 
      s25.state.is_logged = true;
    if($.cookie('s_us_name')) 
      s25.state.my_domain = $.cookie('s_us_name');

  }
}

s25.get_my_info = function () {
  //page load error
  if(!document.domain)
    return -1;

  s25.state.blog_domain = document.domain.replace(/^www\./,'');
  s25.log('blog domain: ' + s25.state.blog_domain);

  s25.check_is_logged();

  postinfo = $('div.post_footer_abuse>a');
  if(postinfo.length && postinfo.first().text()=='zgłoś nadużycie') {
    var scr = postinfo[0].getAttribute('onclick');
    //GM_log(scr);
    s25.state.post_id = parseInt(scr.replace(/Service.reportAbuse\('post', ([0-9]+)\)/,'$1'));
    s25.log('post_id: ' + s25.state.post_id);
  }

 


}

s25.count_watched = function (doc) {

  if(document.location.href.slice(0,s25.consts.watch_page_url.length) == s25.consts.watch_page_url) {
    if(s25.state.watched_cache)
      newcomments = s25.state.watched_cache;
    else
      s25.state.watched_cache = newcomments = s25.parse_watched(doc);
  } else
    newcomments = s25.parse_watched(doc);

  serialize = "";

  s25.state.watched_new_answers = 0;
  for(c=0; c<newcomments.rows.length;c++) {
    s25.state.watched_new_answers += (newcomments.rows[c].ncomments != 0);
    if(newcomments.rows[c].ncomments)
      serialize = (serialize ? (serialize + ":") : "") + newcomments.rows[c].id + '=' + newcomments.rows[c].ncomments;
    //s25.state.watched_new_answers += newcomments.rows[c].ncomments;
  }
  if(s25.state.watched_new_answers > 0) {
    s25.state.watched_first_link = newcomments.rows[0].link + s25.consts.show_last_hash + newcomments.rows[0].ncomments;
    s25.state.watched_first_title = newcomments.rows[0].title + ' (' + newcomments.rows[0].ncomments + ')';
    GM_setValue("watched_first_link", s25.state.watched_first_link);
    GM_setValue("watched_first_title", s25.state.watched_first_title);
  }
  GM_setValue("watched_serialize", serialize);
  GM_setValue("watched_new_answers", s25.state.watched_new_answers.toString());
}


s25.recheck_status = function (force) {
  //s25.log('s25.recheck_status @' + new Date().toTimeString());

  now = new Date().getTime();
  last_check = parseInt(GM_getValue("recheck_time", 0));
  if(force || now - last_check >= s25.consts.update_delay * 1000) {
    //ustaw timer od razu, żeby nie rozpocząć dwóch sprawdzań równolegle
    GM_setValue("recheck_time", now.toString());
    s25.loadPage(s25.consts.watch_page_url, s25.onload_watch_page_info);
  } else {
    //GM_log("-cached-");
    s25.state.watched_first_link = GM_getValue("watched_first_link");
    s25.state.watched_first_title = GM_getValue("watched_first_title");
    s25.state.watched_new_answers = GM_getValue("watched_new_answers",0);
    s25.state.newmails = GM_getValue("newmails",0);
    s25.update_ui();
  }
}

s25.loop_recheck_status = function () {
  
  s25.check_is_logged(); //is_logged może się zmienić w trakcie sesji (wylogowanie z innego okna przeglądarki)
  if(!s25.state.is_logged) 
    return;

  s25.recheck_status(false);

  //sprawdza czterokrotnie w ciągu update_delay (bo może inny wątek odświeżył)
  delay = s25.consts.update_delay * 1000 / 4;
  if(delay<1000) delay = 1000;

  setTimeout(s25.loop_recheck_status, delay);
}

/* Przegląda zapamietane informacje o obserwowanych stronach
 * Jeśli aktualnie wszedłem na jedną ze stron obserwowanych to uznaje, że wszystkie komentarze na niej
 * zostały obejrzane, więc kasuję tę notkę z listy */
s25.offline_update_watched = function () {
  if(s25.state.post_id) {
    serialize = GM_getValue("watched_serialize","");
    //s25.log("serialize: " + serialize,1);
    watched = serialize.split(':');
    for(w=0, match=false, newserialize="";w<watched.length;w++){
      //s25.log("watched: "+ watched[w],1);
      ar = watched[w].split('=');
      id = parseInt(ar[0]);
      count = parseInt(ar[1]);
      if(id == s25.state.post_id) {
       match = true;
      } else 
	//budujemy nową listę pomijając czytaną właśnie notkę
	newserialize = (newserialize ? (newserialize + ':') : "") + watched[w];
    }

    if(match) {
      //s25.log("newserialize: " + newserialize,1);
      //natychmiast zmieniamy to co wiemy
      GM_setValue("watched_serialize", newserialize);
      GM_setValue("watched_new_answers", watched.length-1);
      //wymusamy ponowne sprawdzenie strony obserwowanych (żeby otrzymać nowe linki/tytuły)
      setTimeout(function () { s25.recheck_status(true); }, 1000); //after a second (server lagging) recheck real status
    }
      
  }
}


s25.get_account_info = function () {
  if(!s25.state.is_logged)
    return 0;

  if(document.location.href.slice(0,s25.consts.watch_page_url.length) == s25.consts.watch_page_url)
    s25.analyze_watch_page_info(document);
  else 
    s25.offline_update_watched();

  if(s25.consts.update_delay > 0)
    s25.loop_recheck_status();
}

s25.onload_watch_page_info = function (responseDetails) {
  xmlDoc = new DOMParser().parseFromString(responseDetails.responseText, 'text/xml');
  s25.analyze_watch_page_info(xmlDoc);
}

s25.analyze_watch_page_info = function (doc) {
  //s25.log("s25.analyze_watch_page_info",1);

  s25.count_watched(doc);
  
  //tds = s25.getElementsByClass('new_mails', doc, 'span');
  //s25.state.newmails = tds.length;
  //GM_setValue("newmails", s25.state.newmails.toString());

  //ustaw timer w momencie zakoćzenia sprawdzania
  GM_setValue("recheck_time", new Date().getTime().toString());
  s25.update_ui();
}

s25.parse_watched = function (dom) {
  var newcomm = new Object();
  newcomm.rows = new Array();
  newcomm.sel = new Array();
  var nc = 0;

  //wiersze tabeli z niepustą nazwą klasy
  //rows =  s25.getElementsByCondition(function(el){if(el.className) return el;}, dom.getElementById('posts-comments-watch'), 'tr');
  var rows = $(dom).find('#posts-comments-watch tr');

  for (i = 0; i < rows.length; i++) {
    var row = rows[i];
    if(!row.id) 
      newcomm.header = row;
    else {
      newcomm.rows[nc] = new Object();
      newcomm.rows[nc].id = row.id.slice(row.id.indexOf('-')+1);
      columns = row.getElementsByTagName('td');
      info = columns[0].getElementsByTagName('a')[0];
      newcomm.rows[nc].title = info.innerHTML;
      newcomm.rows[nc].link = info.href;
      newcomm.rows[nc].ncomments = parseInt(columns[3].innerHTML);
      newcomm.rows[nc].xdate = Date.parse(columns[1].innerHTML.replace(/-/g,'/'));
      newcomm.rows[nc].row = row;
      s25.log('watched: ' + newcomm.rows[nc].id + ' ' + newcomm.rows[nc].ncomments + ' '+ newcomm.rows[nc].link + ' ' + newcomm.rows[nc].title);

      nc++;
    }
  }
  return newcomm;
}


s25.lprunning = 0;

function event_watched_del_done(responseDetails) {
  s25.lprunning--;
  s25.log('lpdone, running: ' + s25.lprunning);
}


s25.islpdone = function (whendone, timeouts, wait) {
  s25.log('timeout ' + wait + ' x ' + timeouts + ' s25.lprunning ' + s25.lprunning);
  
  if(timeouts<=0 || s25.lprunning<=0) {
    whendone();
    return 0;
  }

  setTimeout(function () {s25.islpdone(whendone, --timeouts, wait);}, wait);
}


s25.event_watched_del_selected = function (e) {

  e.preventDefault();

  if(this.style.color!='red') {
    this.innerHTML = 'na pewno usunąć z listy obserwowanych?'; 
    this.style.color='red';
    return 0;
  } else {
    this.innerHTML = 'usuwam zaznaczone z listy obserwowanych'; 
    this.style.color='gray';
  }
 

  var list = s25.state.watched_cache.sel;
  for(var i=0; i<list.length;i++) {
    if(list[i].checked) {
      s25.lprunning++;
      s25.log('lpgo, running: ' + s25.lprunning);
      id = list[i].name.slice(3);
      s25.loadPage('http://admin.nowyekran.pl/comments-watch-deletepost-json/' + id, event_watched_del_done, event_watched_del_done);
    }
  }

  this.style.backgroundImage = 'url(' + s25.media.throbbericon + ')';
  this.style.backgroundRepeat = 'no-repeat';
  this.style.paddingLeft = '16px';
  this.style.backgroundPosition = 'left 1px';
  var whendone = document.location.reload;
  s25.islpdone(whendone,10,1000);

}



s25.update_watched_page = function () {
  if(document.location.href.slice(0,s25.consts.watch_page_url.length) != s25.consts.watch_page_url)
    return;

  if(!s25.state.watched_cache)
    s25.state.watched_cache = s25.parse_watched(document);

  for (i = 0; i < s25.state.watched_cache.rows.length; i++) {
    watch = s25.state.watched_cache.rows[i];

    //dodaj link do pierwszego niewidzianego komentarza
    if(watch.ncomments>0) {
      a = s25.createLink(watch.link + s25.consts.show_last_hash + watch.ncomments, watch.ncomments.toString());
      a.setAttribute('style', 'color: inherit !important');
      td = watch.row.getElementsByTagName('td')[3];
      td.replaceChild(a,td.firstChild)
    }


  }

  //sortowanie obserwowanych według postów *i daty powstania notki*
  //(tylko jeśli nie włączono żadnych opcji sortowania)
  if(document.location.href == s25.consts.watch_page_url) {
    wrsort = function (a,b) { 
      if(a.ncomments != b.ncomments)
	return b.ncomments - a.ncomments;
      else 
	return b.xdate - a.xdate;
    };

    s25.state.watched_cache.rows.sort(wrsort);

    watchtable = document.getElementById('posts-comments-watch').getElementsByTagName('table')[0];
    while(watchtable.rows.length>1)
      watchtable.deleteRow(1);

    tbody = watchtable.getElementsByTagName('tbody')[0];
    for (i = 0; i < s25.state.watched_cache.rows.length; i++) {
      s25.state.watched_cache.rows[i].row.className = 'r' + i%2;
      tbody.appendChild(s25.state.watched_cache.rows[i].row);
    }
  }

  //multiple delete from watched
  var append_cb = true;
  append_cb = false;


  if(append_cb) {
    $('div@posts-comments-watch>table th').first().attr('colspan', 2);

    for (i = 0; i < s25.state.watched_cache.rows.length; i++) {
      watch = s25.state.watched_cache.rows[i];

      var cb = document.createElement('input');
      cb.type='checkbox';
      cb.name='ws-' + watch.id;
      s25.state.watched_cache.sel.push(cb);
      
      var cell = document.createElement('td');
      cell.appendChild(cb);

      watch.row.insertBefore(cell, watch.row.firstChild);



    }

    var delall = s25.elem('a', { id: 'delall', style: { color: 'gray' }, href: '#watched-del-selected' }, ["usuń zaznaczone z listy obserwowanych"]);
    s25.addEvent(delall, 'click', s25.event_watched_del_selected);
    $('div@posts-comments-watch>table.item-list').first().after(s25.elem('div',{}, [delall]));

  }

  //
  if(0){
    for (i = 0; i < s25.state.watched_cache.rows.length; i++) {
      var link = s25.createLink('#rem', 'x');
      link.id='del-' + s25.state.watched_cache.rows[i].id;
      s25.addEvent(link, 'click', function(e) { s25.loadPage('http://admin.nowyekran.pl/comments-watch-deletepost-json/' + this.id.split('-')[1], event_watched_del_done, event_watched_del_done); } );
      $(s25.state.watched_cache.rows[i].row).find('td').last().append(link);
//      s25.loadPage('http://admin.nowyekran.pl/comments-watch-deletepost-json/' + s25.state.watched_cache.rows[i].id, event_watched_del_done, event_watched_del_done);
    }
  }
}



s25.update_menu = function () {
  menu = $('div@header>div.session_header>div.session_status');
  if(!menu.length) return 1;

  
  //dodaj 'obserwowane' do menu
  if(s25.state.is_logged) {
    //delayed add to menu - otherwise endless loop in for
    s25.state.watched_link = s25.createLink('http://admin.nowyekran.pl/posts-comments-watch/', 'Obserwowane');
    s25.state.watchedcount_link = s25.elem('a', { style: { marginLeft: 0, paddingLeft: ".5em", background: 'none', cursor:'pointer', color: 'red', display: 'none'}}, ["(0)"]);
    //jeśli nowy komentarz jest w tej samej notce i nie zmienia się URL, to trzeba odświeżyć stronę - inaczej ani komentarz nie będzie widoczny, ani nie zadziała #show-laet-
    s25.addEvent(s25.state.watchedcount_link, 'click', function(e) { if(this.href.split('#')[0] == document.location.href.split('#')[0]) { e.preventDefault(); document.location.href = this.href; document.location.reload(); }} );
    s25.update_ui_watched();

    $('a#session_status-mails').after(s25.state.watchedcount_link).after(s25.state.watched_link);
  }
}

s25.update_stars = function () {
  if(GM_getValue('hide_stars', false)) {
    $('div.stars_box').hide();
    if(s25.state.post_id) $('div.post_footer_stars').hide();
  }
}


s25.update_post_page = function () {
}

s25.update_comments = function () {
  
  //extend_comment_form();
  //s25.add_buttons();

  cinfo = s25.parse_comments();
  if(!cinfo) return -1;

  //for(c=0;c<cinfo.length;c++)
  //  s25.update_comment(cinfo[c]);

  s25.update_comments_jumpto(cinfo);

  //post_comment = s25.getElementByClass('ico_write_comm', document, 'a');
  //if(post_comment)
  //  post_comment.setAttribute('onclick', post_comment.getAttribute('onclick').replace(/(\);return false;)/, ', "@' + s25.state.blog_author_name + '"$1'));
 
  return 0;
}

s25.parse_comments = function () {

  var cinfo = new Array();
  var comments = $('ul.comments_list>li.comment');
  var comment_no;

  for(comment_no=0,child=0;child<comments.length;child++) {

    cinfo[comment_no] = new Object();

    var comment = cinfo[comment_no];
    comment.li = comments[child];


    comment.commentname = $(comment.li).attr('id');
    comment.commentid = comment.commentname.split('_')[1];
    var author = $(comment.li).find('.post_author_link');
    comment.author_domain = author[0].host;
    comment.author_nick = author.text();
    comment.author_id = 0;
    var cl = $(comment.li).attr('class').split(' ');
    for(var cli =0; cli < cl.length; cli++)
      if(cl[cli].slice(0,6) == 'caoid-')
	comment.author_id = cl[cli].slice(6);

    //comment.comment_text_tag
    comment.navi_tag = $(comment.li).find('.comment_options');

    //GM_log('comm: ' + comment.commentname + ' ' + comment.commentid + ' ' + comment.author + ' ' + comment.author_domain + ' ' + comment.author_nick + ' ' + comment.author_id);

    comment_no++;
  }

  return cinfo;
}

//process jump to comment directive (#show-last-n)
s25.update_comments_jumpto = function (cinfo) {
  if(!cinfo.length) {
    //GM_log("No comments available");
    return;
  }

  if(document.location.hash.indexOf(s25.consts.show_last_hash) != 0)
    return;
  
  //s25.log(document.location.hash);
  jumpto = cinfo.length - parseInt(document.location.hash.slice(s25.consts.show_last_hash.length));
  
  //document.location.hash = cinfo[jumpto].commentname;
  //s25.log(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
  document.location.replace(document.location.href.split('#')[0] + '#' +  cinfo[jumpto].commentname);
}


s25.update_ui = function () {
  s25.update_ui_watched();
  //s25.update_ui_newmails();
}

 
s25.update_ui_watched = function () {
  s25.log('new answers: ' + s25.state.watched_new_answers);
  if(!s25.state.watched_link)
    return;
  if(s25.state.watched_new_answers > 0) {
    //s25.state.watched_link.innerHTML = 'obserwowane ('+ s25.state.watched_new_answers + ')';
    s25.state.watched_link.style.color='red';
    s25.state.watchedcount_link.innerHTML = '('+ s25.state.watched_new_answers + ')';
    s25.state.watchedcount_link.href = s25.state.watched_first_link;
    s25.state.watchedcount_link.title = s25.state.watched_first_title;
    s25.state.watchedcount_link.style.display ='inline';


  } else {
    s25.state.watched_link.innerHTML = 'Obserwowane';
    s25.state.watched_link.style.color='';
    s25.state.watchedcount_link.style.display ='none';
  }

}

s25.update_div = function (nver) {

  div = document.createElement('div');
  div.id = 'verupdate';
  ln1 = document.createElement('span');
  ln1.style.fontWeight='bold';
  ln1.appendChild(document.createTextNode('Uwaga, pojawiła się nowsza wesja skryptu ' + s25.meta.name));
  ln1.appendChild(document.createElement('br'));
  ln2 = document.createElement('span');
  ln2.appendChild(document.createTextNode('Aktualnie używasz wersji: ' + s25.meta.version + ', a najnowasza wersja to ' + nver));
  ln2.appendChild(document.createElement('br'));
  ln2.appendChild(document.createElement('br'));
  ln3 = document.createElement('span');
  ln3.appendChild(document.createElement('br'));
  ln3.appendChild(document.createTextNode('Zobacz '));
  ln3.appendChild(s25.createLink(s25.consts.project_url, 'stronę projektu ' + s25.meta.name));
  ln3.appendChild(document.createTextNode(' żeby zobaczyć co się zmieniło.'));
  ln3.appendChild(document.createElement('br'));
  ln3.appendChild(document.createElement('br'));
  ln4 = document.createElement('span');
  //if(s25.state.is_ff_extension)
  //  ln4.appendChild(s25.createLink('http://dl.dropbox.com/u/15707854/salon25.xpi', 'Zaktualizuj do najnowszej wersji'));
  //else
    ln4.appendChild(s25.createLink('http://salon25.googlecode.com/svn/tags/ne/v' + nver + '/salon25ne.user.js', 'Zaktualizuj do najnowszej wersji'));
  ln4.appendChild(document.createElement('br'));
  ln5 = document.createElement('div');
  ln5.style.textAlign = 'right';
  link = s25.createLink('#', 'Zamknij okno');
  s25.addEvent(link, 'click', function(e) { document.getElementById("verupdate").style.display="none"; e.preventDefault(); } );
  ln5.appendChild(link);
  ln5.appendChild(document.createElement('br'));

  div.appendChild(ln1);
  div.appendChild(ln2);
  div.appendChild(ln4);
  div.appendChild(ln3);
  div.appendChild(ln5);

  div.style.position = 'fixed';
  div.style.padding = '1em';
  div.style.backgroundColor = '#ffcccc';
  div.style.border = '2px solid red';
  div.style.top = '2em';
  div.style.left = '2em';

  document.getElementsByTagName('body')[0].appendChild(div);
}

s25.versionToInt = function (ver) {
  a = ver.split('.');
  return a[0] * 1000000 + a[1] * 1000 + a[2] * 1;
}

s25.onload_version_check_notify = function (responseDetails) {
  nver = responseDetails.responseText;
  GM_log("Current version is: " + s25.meta.version + " (" + s25.versionToInt(s25.meta.version) + ")");
  GM_log("Newest version is: " + nver + " (" + s25.versionToInt(nver) + ")");
  if(s25.versionToInt(nver) > s25.versionToInt(s25.meta.version))
    s25.update_div(nver);
}

s25.check_updates = function (force_check, action) {
  
  d=new Date();
  now = d.getTime();
  
  if(force_check)
    check = true;
  else {
    if(!GM_getValue('version_check_enabled', true))
      return;
    period = GM_getValue("version_check_delay", -1); //delay between checks (in seconds)
    if(period == -1) {
      period = 24 * 3600;
      GM_setValue("version_check_delay", period);
    }
    last = parseInt(GM_getValue("version_check_last", "0"));
    
    check = (last + period*1000) < now;
    //GM_log('previous check was at ' + ((now - last)/3600000) + ' hours ago; check = ' + check);
  }
  

  //GM_log('check ' + last + ' + ' + period + ' * 1000 - ' + now + ' = ' + (last + period*1000 - now));
  if(check) {
    GM_log('checking version update');
    GM_setValue('version_check_last', now.toString());

    s25.loadPage(s25.consts.version_check_url, action);
  }

}

s25.change_yesno = function (link, e) { 
  e.preventDefault(); 
  variable=link.getAttribute('variable'); 
  config_name=link.getAttribute('config_name'); 

  if(link.innerHTML == "ON" || link.innerHTML=='TAK')
    oldval = 1;
  else
    oldval = 0;

  //GM_log('change: was ' + oldval);

  val = !oldval;

  //GM_log('change: new ' + val);


  //GM_log('change: onchange new ' + val);

  if(val == oldval)
    return;

  link.innerHTML = val?"TAK":"NIE";

  if(variable != null)
    eval(variable + ' = ' + val + ';');
  if(config_name)
    GM_setValue(config_name, val);

  //GM_log('change: variable ' + variable + ' config_name ' + config_name);
  if(config_name)
    ;//GM_log(config_name + 'is ' + GM_getValue(config_name, 'unknown'));
  return val;

} 

s25.event_change_yesno = function (e) {
  s25.change_yesno(this, e);
  return false;
}
s25.ev_update_menu = function (e) { 
  s25.change_yesno(this, e);
  s25.apply_menu_look();
  return true;
}

/* Functions adds one On/Off setting to the menu and attaches handlers when the stat changes
 * 
 * variable - variable name (passed as string) connected to the setting
 * config_name - persistent (GM) setting name connected to the setting
 * onchange - callback function called with an event handler when state was changed
 *            should call s25.change_yesno(this, event) first and use return value as the actual value
 * one of three above should be set, remaining can be null (but all not-null will be processed)
 * defaultval - default value used if neither 'variable' nor 'config_name' returned any
 */
s25.menu_yesno_add = function (menu, mtitle, variable, config_name, onchange, defaultval) {

  tr= document.createElement('tr');
  title = document.createElement('td');
  value  = document.createElement('td');
  avalue = document.createElement('a');
  avalue.style.cursor = 'pointer';

  title.innerHTML = mtitle;

  if(variable!=null) 
    val = eval(variable);
  else if(config_name)
    val = GM_getValue(config_name, defaultval);
  else 
    val = defaultval;

  avalue.innerHTML = (val==1) ? 'TAK' : 'NIE';

  if(variable!=null)    avalue.setAttribute('variable', variable);
  if(config_name!=null) avalue.setAttribute('config_name', config_name);

  if(onchange!=null)
    s25.addEvent(avalue, 'click', onchange);
  else
    s25.addEvent(avalue, 'click', s25.event_change_yesno);


  title.style.width='250px';
  value.style.width='70px';
  tr.appendChild(title);
  value.appendChild(avalue);
  tr.appendChild(value);

  menu.appendChild(tr);

}

s25.menu_ro_add = function (menu, mtitle, mvalue) {

  tr= document.createElement('tr');
  title = document.createElement('td');
  value  = document.createElement('td');

  title.innerHTML = mtitle;
  value.innerHTML = mvalue;
  value.style.color = '#666';

  title.style.width='250px';
  value.style.width='70px';
  tr.appendChild(title);
  tr.appendChild(value);

  menu.appendChild(tr);

}

s25.menu_section = function (menu, mtitle) {
  tr= document.createElement('tr');
  title = document.createElement('th');
  title.innerHTML = mtitle;
  title.style.width='1000%';
  title.style.backgroundColor = '#ddd';
  title.style.border = '0px';
  title.style.borderBottom = '1px solid black';
  title.colSpan=2;
  tr.appendChild(title);
  menu.appendChild(tr);
}

s25.ev_reset_settings = function (e) {
  on = s25.change_yesno(this, e);
  if(on) {
    var keys = GM_listValues();
    for (var i=0, key=null; key=keys[i]; i++) {
      GM_deleteValue(key);
    }
    document.location.reload();
  }
}

s25.options_add_menu = function (where, showadvanced) {
  var adv = showadvanced || GM_getValue('menu_advanced', false);
  menu = document.createElement('div');
  menu.style.width='320px';
  menu.style.backgroundColor = '#eee';

  table = document.createElement('table');
  table.style.width='100%';

  s25.menu_section(table, 'Strona Główna');
  s25.menu_yesno_add(table, 'Ukryj awatary autorów', null, "sg_hide_avatars", null, 0);
  s25.menu_yesno_add(table, 'Eksperymentalne: layout SG', null, "sg_columns", null, 0);
  s25.menu_section(table, 'Różne');
  s25.menu_yesno_add(table, 'Ukryj gwiazdko-oceny', null, "hide_stars", null, 0);
  s25.menu_yesno_add(table, 'Nie wylogowywuj po wyjściu z przeglądarki', null, "persistent_login", null, 0);
  s25.menu_section(table, 'Konfiguracja');
  s25.menu_yesno_add(table, 'Zresetuj konfigurację', null, null, s25.ev_reset_settings, 0);
  s25.menu_yesno_add(table, 'Debug', null, "debug", null, 0);
  if(adv) {
    s25.menu_yesno_add(table, 'Sprawdzaj aktualizacje ' + s25.meta.name, null, "version_check_enabled", null, 1);
    s25.menu_ro_add(table, 'Sprawdzaj co', GM_getValue('version_check_delay', '?')/3600 + 'h');
    s25.menu_section(table, 'Zaawansowane');
    s25.menu_yesno_add(table, 'Pokaż zaawansowane', null, "menu_advanced", null, 0);
  }

  menu.appendChild(table);
 

  where.appendChild(menu);

  //s25.options_comment_template(where);

}

s25.onload_version_check_options_update = function (responseDetails) {
  nver = responseDetails.responseText;

  span = document.getElementById('options-ver');
  if(!span) return;

  text = document.createTextNode('Najnowsza dostępna wersja to ' + nver + ' ');
  span.replaceChild(text, span.firstChild);
  if(s25.versionToInt(nver) > s25.versionToInt(s25.meta.version)) {
    //if(s25.state.is_ff_extension)
    //  a = s25.createLink('http://dl.dropbox.com/u/15707854/salon25.xpi', '[ZAINSTALUJ]');
    //else
      a = s25.createLink('http://salon25.googlecode.com/svn/tags/ne/v' + nver + '/salon25ne.user.js', '[ZAINSTALUJ]');
    a.style.color = 'blue';
    span.style.color = 'red';
    span.appendChild(a);
  }
  else
    span.style.color = 'green';
}

s25.options_add_footer = function (where) {
  div = document.createElement('div');
  div.style.color = 'gray';
  div.style.marginTop = '3em';
  div.appendChild(document.createTextNode('nowości odnośnie projektu w lubczasopiśmie: '));
  div.appendChild(s25.createLink('http://lubczasopismo.salon24.pl/extensions/', 'Dodatki dla salonu24'));
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createTextNode('strona projektu: '));
  div.appendChild(s25.createLink(s25.consts.project_url, s25.consts.project_url));
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createTextNode('kontakt z autorami: '));
  div.appendChild(s25.elem('span', {style: {color: 'black'}}, ['Jan Słupski (', s25.createLink('http://follow.salon24.pl/','follow'), ') & ', s25.createLink('http://greasemonkey.salon24.pl/', 'greasemonkey')]));
  where.appendChild(div);
}

s25.options_add_lead = function (where) {

  div = document.createElement('div');
  div.appendChild(s25.elem('h2', {}, [s25.meta.name]));
  div.appendChild(document.createTextNode('wersja ' + s25.meta.version));
  div.appendChild(document.createElement('br'));
  span = document.createElement('span');
  span.id = 'options-ver';
  a = s25.createLink(s25.consts.version_check_url, 'sprawdź czy dostępna jest nowsza wersja &rarr; ');
  a.style.cursor = 'pointer';
  a.style.color = 'gray';
  s25.addEvent(a, 'click', function (e) { e.preventDefault(); this.innerHTML = 'sprawdzam'; s25.check_updates(true, s25.onload_version_check_options_update); } );
  span.appendChild(a);
  div.appendChild(span);

  where.appendChild(div);
  where.appendChild(document.createElement('br'));

}

s25.ev_show_options_page = function (e) {
  e.preventDefault(); 
  document.location.hash = '#salon25';

  s25.state.advanced_menu_magic++;

  s25.show_options_page();
}

s25.show_options_page = function () {
  var area = $('#content .content-left-column-right')[0];
  if(s25.undef(area)) area = $('#content .content-full')[0];
  if(s25.undef(area)) return;

  var narea = s25.elem('div', {id: 'salon25-config', className:'content-left'}, [s25.elem('h1', {innerHtml:s25.meta.name})]);

  s25.options_add_lead(narea);
  s25.options_add_menu(narea, s25.state.advanced_menu_magic>=10);
  s25.options_add_footer(narea);
 
  $(area).replaceWith(narea);

  $("a[href='http:///']").attr('href','#');
}


s25.options_page = function () {
  if(document.location.href.slice(0,s25.consts.admin_url.length) == s25.consts.admin_url && document.location.hash == '#salon25') {
    s25.show_options_page();
  }

  s25.options_page_toolbar_entry();
}


s25.options_page_toolbar_entry = function () {

  if(document.location.href.slice(0,s25.consts.admin_url.length) != s25.consts.admin_url)
    return;

  nav=document.getElementById('navigation1');
  if(!nav) return;


  konfig_a = s25.createLink('/settings-account/#salon25', 'Konfiguracja', {style: {cursor: 'pointer'}});
  s25.addEvent(konfig_a, 'click', s25.ev_show_options_page);
  konfiguracja = s25.elem('li', null, [konfig_a]);

  listaopcji = [konfiguracja];

  menu_s25_a = s25.createLink('/settings-account/#salon25', s25.meta.name, {className: 'head', id: 's25menu'});
  menu_s25 = s25.elem('li', null, [menu_s25_a, s25.elem('ul', {style: {display: 'block'}}, listaopcji)]);

  nav.appendChild(menu_s25);

  
}


s25.persistent_login = function () {

  s25.state.persistent_login = GM_getValue('persistent_login', 0);

  var servlogin = unsafeWindow.Service.login;

//GM_getValue('persistent_login', false)?'checked':null 
  unsafeWindow.Service.login = function (_dest_url, _error_url) {
    servlogin(_dest_url, _error_url);
    var perscb = s25.elem('input', { type: 'checkbox', id: 'persistent_login', checked: s25.state.persistent_login?'ckecked':null, style: { top: '1px', position: 'relative' } });
    s25.addEvent(perscb, 'change', function (e) { GM_setValue('persistent_login', this.checked); });
    var perslabel = s25.elem('label', { for: 'persistent_login', style: { cssFloat: 'none', display: 'inline', width: '100%', paddingLeft: '2px',  } }, [ "Nie wylogowywuj po wyjściu z przeglądarki" ]);
    var persdiv = s25.elem('p', {}, [ perscb, perslabel ]);
    $('form#service_login div.cb').before(persdiv);
  };

  if(!s25.state.is_logged)
    return;

  if(GM_getValue('persistent_login', false)) {
    var days = 7;
    var coo = [ 's_us_nick', 's_us_id', 'w_fpost', 'PHPSESSID' ];

    for(var c in coo)  {
      var key = coo[c];
      var val = $.cookie(key);
      if(val)
	$.cookie(key, val, { expires: days, path: '/', domain: s25.consts.domain } );
    }
  }

}

s25.mpage_unnamed_block_title = function () {

  h = $('.content-right-column>.box>.box-header').first().clone();
  h.find('h3').html('NIEWIEMCO');
  $('..content-right-column>.sg_featured_posts_body').first().before(h);
}
 
s25.columns = function () {
  if(!GM_getValue("sg_columns", false)) return;
  if(!s25.URL.matches('http://nowyekran.pl/$') && !s25.URL.matches('http://www.nowyekran.pl/$')) return;
  var nc = document.createElement('div');
  nc.style.width = '300px';
  nc.style.position = 'absolute';
  nc.style.left='1000px';
  $('.layout_service_mainpage').css('position', 'relative');
  $('.layout_service_mainpage .cb').before(nc);
  $('.content-right-column>.box:first').attr('id','recent-posts').appendTo(nc);


  $('a.post_list_category').hide();

  
  $('.news-category-container a.image').hide();
  $('.news-category-container a').css('color', 'black').css('font-weight', 'normal');

  $('.news-category-list>li:first').hide();

  var news = document.createElement('div');
  news.id = 'newsColumn';
  news.style.width = '300px';
  news.style.position = 'absolute';
  news.style.left='1000px';
  $('#breaking').css('position', 'relative');
  $('#breaking').prepend(news);
  $('ul.news-category-list').appendTo(news);
  $('li.news-category-container').css('border-bottom', 'none');

  $('#header').css('margin', '0 20px');
  $('#footer').css('margin', '0 20px');
  $('#breaking').css('margin', '0 20px');
  $('#content').css('margin', '0 20px');

  $('#autorzy-dzisiaj-nowy li').each(function() { 
    var li = $(this);
    li.find('.post_content').html(li.find('.post_content>strong').html());
    li.find('div.post_author').prepend(li.find('a.post_author_link')); 
    li.find('a.post_author_link:last').css('color','gray').css('padding-left','0.3em').css('font-style','italic'); 
  });


  s25.sg_buttons();


}


s25.sg_buttons = function() {
  var h2 = document.createElement('h2');
  h2.innerHTML = 'Narzędzia';

  $('#newsColumn').append(h2);


  var b = document.createElement('a');
  s25.addEvent(b, 'click', s25.del_sg_images);
  b.innerHTML = 'img';

  $('#newsColumn').append(b);


}

s25.del_sg_images = function () {
  $('.sg_featured_posts_body .post_list_image_item img').hide();
  $('.stars_box').hide();
  $('div.sg_last_post_body ul.post_list li p.post_content img').hide();
}



s25.newposts = function () {
  if(!s25.URL.matches('http://nowyekran.pl/$') && !s25.URL.matches('http://www.nowyekran.pl/$')) return;

  var posts = [];
  var post_count = 0;

  console.log('s25.posts');


  var where = $('div#recent-posts').first();
  var ul;

  var more = document.createElement('a');
  s25.addEvent(more, 'click', fetch_posts);
  more.innerHTML = 'Więcej';
  $(where).append(more);

  function fetch_posts() {
    $(more).hide();
    ul = document.createElement('ul');
    ul.id = 'new-new-posts';
    ul.className = 'post_list';
    $(where).append(ul);
    $.get('http://www.nowyekran.pl/archive/', query_archive);
  }

    
  function append_post(post, num) {
    if(num<20) //number of posts already displayed
      return;
    var p = $(post?post:this);

    var li = document.createElement('li');
    $(li).append(p.find('h2'));
    $(li).append(p.find('.post_author'));
    $(ul).append(li);

  }

  function parse(data) {
    //return $($.parseXML(data));
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = data.replace(/<script(.|\s)*?\/script>/g, '');
    return $(tempDiv);
  }

  function append_archive(data) {
    var archive = parse(data);//$($.parseXML(data));

    var newposts = archive.find('ul.post_list>li');

    for(var i=newposts.length-1; i>=0;i--) {
      posts.push(newposts[i]);
      append_post(newposts[i], post_count++);
    }

    var prev = archive.find("a.pg_prev").first().attr('href');

    if(prev && post_count < 100)
      $.get('http://www.nowyekran.pl' + prev, append_archive);
    //else
      //update_archive(where);
  }

  function query_archive(data) {
    var archive = $($.parseXML(data));
    var last = archive.find("a.pg_last").first().attr('href');

    if(last)
      $.get('http://www.nowyekran.pl' + last, append_archive);

  }


}

s25.init_after_s24 = function () {
  s25.update_menu();

  if($('#salon25-config').size())
    $('#navigation1').accordion("activate", $('#s25menu'));
}

s25.after_s24_init_hooks = function () {
  $().ready( s25.init_after_s24 );
}

s25.main = function () {
  if(!s25.URL.matches('http://[^/]*nowyekran.pl.*')) return;

  s25.init();


  s25.check_updates(false, s25.onload_version_check_notify);

  s25.get_my_info();
  s25.get_account_info();
  s25.options_page();

  s25.persistent_login();

  s25.update_post_page();
  s25.update_comments();


  //rebuild_ne_main_page();
  s25.update_footer();
  s25.update_mpage();
  s25.update_stars();
  s25.update_watched_page();
  s25.columns();
  s25.newposts();
  s25.after_s24_init_hooks();
}



s25.main();
